<?php
namespace app\mobile\controller;

use app\mobile\model\Member;
use app\mobile\model\MemberOrder;
use app\mobile\model\ShopGoods;
use app\mobile\model\Image;
use app\mobile\model\Shop;
use app\mobile\model\ShopGoodsEvaluate;
use think\Cache;
use think\Db;
use think\Request;
use think\Session;


/**
 * Class ShopAuth
 * @package app\mobile\controller 店铺认证
 */
class ShopAuth extends BaseController
{
    /*
     * 店家登录
     */
    public function login(Request $request)
    {
        if ($request->isPost()){
            $result = (new Member())->login_auth();
            if ($result['code'] == 200){
                //查看是否为店主
                $shop_status = (new Shop())
                    ->where(['member_id' => Session::get('member_id')])
                    ->value('status');
                if (!$shop_status){
                    return ['code' => 204, 'message' => '登录成功,正在跳转...'];
                }else{
                    switch ($shop_status){
                        case 1:  //成功开店
                            return ['code' => 200, 'message' => '登录成功,正在跳转...'];
                        case 3: //等待认证
                            return ['code' => 202, 'message' => '登录成功,正在跳转...'];
                        case 2: //失败
                            return ['code' => 203, 'message' => '登录成功,正在跳转...'];
                    }
                }
            }else{
                return ['code' => 500,'message' => $result['message']];
            }
        }
        return $this->fetch('');
    }

    /*
     * 店铺注册
     */
    public function register(Request $request)
    {
        if ($request->isPost()){
            $data = $request->post();
            if (!Cache::has('reg_code')){return ['code'=>0,'message'=>'验证码已失效,请重新获取'];}

            $code = Cache::get('reg_code');

            if ($code == $data['yzm']){
                $model = new Member();
                $arr = $model->where('username',$data['username'])->find();
                if ($arr){return ['code'=>0,'message'=>'此账户已存在'];}
                if (count(explode(' ',$data['password'])) > 1){ return ['code' => 401, 'message' => '密码含空格'];}
                //执行注册
                $res = (new Member())->reg();
                if ($res){  //已成功注册为网站会员
                    //生成一张专属二维码
                    (new ScanCode())->qrcodeWithPicture($res);
                    //注册店铺
                    $map['member_id'] = $res;  //会员id和店铺id绑定
                    $shop_res = (new Shop())->allowField(true)->save($map);
                    Session::set('member_id',$res);  //生成全局会员id
                    return $shop_res ? ['code' => 200 , 'message' => '注册成功']:['code' => 500 , 'message' => '网络繁忙,请重试'];
                }else{   //注册会员失败
                     return ['code' => 500, 'message' => '网络繁忙,请重试'];
                }
            }else{
                return ['code'=>0,'message'=>'验证码不正确'];
            }
        }
    }

    /*
     * 认证等待页
     */
    public function create_wait()
    {
        return $this->fetch();
    }
    /*
     * 认证失败页
     */
    public function create_fail()
    {
        //用户失败原因
        $reason = Shop::where(['member_id' => Session::get('member_id')])->value('reason');
        return $this->fetch('',[
            'reason' => $reason,
        ]);
    }

    /*
     * 认证数据录入
     */
    public function index(Request $request)
    {
        if ($request->isPost()){
            //检测是否勾选管理协议
            if (!$request->has('deal','post'))return ['code'=>0,'message'=>'请阅读并同意平台管理协议!'];
            $shop = new Shop();
            $data = $shop->index_query();
            $data['member_id'] = Session::get('member_id');
            $data['type_id'] = 1;
            $result = $shop->validate('Shop.auth')->isUpdate(true)->save($data);
            if ($result){
                return ['code'=>200,'message'=>'提交成功'];
            }else{
                return ['code'=>0,'message'=>$shop->getError()];
            }
        }
        return $this->fetch('index');
    }
    /*
     * 协议内容
     */
    public function deal_content()
    {
        return $this->fetch('');
    }
    /*
     * 创建店铺
     */
    public function create_shop(Request $request)
    {
        if ($request->post()){
            $shop = new Shop();
            $data = $shop->create_shop_query();
            $data['member_id'] = Session::get('member_id');
            $data['description'] = '';
            $data['reason'] = '';
            $result = $shop->allowField(true)->validate('shop.create')->save($data);
            return $result?['code'=>200,'message'=>'提交成功']:['code'=>0,'message'=>$shop->getError()];
        }
        return $this->fetch('');
    }
    /*
     * 我的店铺
     */
    public function member_shop(Request $request)
    {
        $info = (new Shop())
            ->where('member_id',Session::get('member_id'))
            ->field('member_id,banner,logo,title')
            ->with(['memberOrder'=>function($e){
                $e->field('id,shop_id,freight,status')
                  ->whereTime('create_time','today');
            }])
            ->find();

        //今日成交总额
        $total = 0;
        if (!empty($info)){
            foreach ($info->memberOrder as $v){
                foreach ($v->memberOrderAttached as $vv){
                    $total += $vv['price']*$vv['number']+$v['freight'];
                }
            }
        };
        return $this->fetch('',[
            'total'     =>  $total,
            'info'      =>  $info,
            'count'     =>  count($info->memberOrder),
        ]);
    }
    /*
     * ajax定时检查评论
     */
    public function check_msg(Request $request)
    {
        if ($request->isPost()){
            $map['member_id'] = Session::get('member_id');
            $newMsg = (new Shop())->where($map)
                ->field('member_id')
                ->with(['shopGoods'=>function($e){
                    $e->field('member_id,id');
                }])
                ->find();
            $validNum = 0;
            foreach ($newMsg->shopGoodsEvaluate as $v){
                if ($v['examine'] == 2){
                    $validNum++;
                }
            }
            return $validNum == 0 ? ['code'=>0] : ['code'=>200] ;
        }
    }
    /*
     * 店铺信息
     */
    public function shop_info(Request $request)
    {
        //查找本店铺的信息
        $info = (new Shop())
            ->where('member_id',Session::get('member_id'))
            ->find();
        return $this->fetch('',[
            'info'  =>  $info,
            'domain'    =>  $request->domain(),
        ]);
    }
    /*
     * 更改上传店铺logo
     */
    public function upload_logo(Request $request)
    {
        if ($request->isPost()){
            $path = (new Image())->one_img_upload('file','createShop');
            $result = (new Shop())
                ->where('member_id',Session::get('member_id'))
                ->update(['logo'=>$path]);
            return $path && $result?['code'=>200,'message'=>DS.$path]:['code'=>0,'message'=>'上传头像失败'];
        }
    }


    /*
     * 修改店铺名称
     */
    public function edit_shop_name(Request $request)
    {
        if ($request->isPost()){
            $data['title'] = $request->post('title');
            $shop = new Shop();
            $result = $shop
                ->isUpdate(true)
                ->validate('shop.create')
                ->where('member_id',Session::get('member_id'))
                ->update($data);
            return $result||$result === 0?['code'=>200,'message'=>'修改成功']:['code'=>0,'message'=>$shop->getError()];
        }
        return $this->fetch('');
    }
    /*
     * 店铺简介
     */
    public function edit_shop_description(Request $request)
    {
        $description = Shop::where(['member_id' => Session::get('member_id')])->value('description');
        if ($request->isPost()){
            //更改简介
            $result = Shop::where(['member_id' => Session::get('member_id')])
                ->update(['description' => $request->post('description')]);
            return $result||$result === 0 ? ['code' => 200 , 'message' => '修改成功'] :[ 'code' => 0 ,'message'=>'修改失败'];
        }

        return $this->fetch('',[
            'description' => $description,
        ]);
    }
    /*
     * 发货地址
     */
    public function edit_shop_ship(Request $request)
    {
        //查找用户的发货地址
        $ship_address = Shop::where(['member_id' => Session::get('member_id')])->value('ship_address');
        if ($request->isPost()){
            //更改收货地址
            $result = Shop::where(['member_id' => Session::get('member_id')])
                ->update(['ship_address' => $request->post('ship_address')]);
            return $result||$result === 0 ? ['code' => 200 , 'message' => '修改成功'] :[ 'code' => 0 ,'message'=>'修改失败'];
        }
        return $this->fetch('',[
            'ship_address'  => $ship_address,
        ]);
    }
    /*
     * 退货地址
     */
    public function edit_shop_refund(Request $request)
    {
        //查找用户的退货地址
        $refund_address = Shop::where(['member_id' => Session::get('member_id')])->value('refund_address');
        if ($request->isPost()){
            //更改退货地址
            $result = Shop::where(['member_id' => Session::get('member_id')])
                ->update(['refund_address' => $request->post('refund_address')]);
            return $result||$result === 0 ? ['code' => 200 , 'message' => '修改成功'] :[ 'code' => 0 ,'message'=>'修改失败'];
        }
        return $this->fetch('',[
            'refund_address' => $refund_address,
        ]);
    }
    /*
     * 持卡人姓名
     */
    public function edit_shop_bank_name(Request $request)
    {
        //查找用户的持卡人姓名
        $bank_name = Shop::where(['member_id' => Session::get('member_id')])->value('bank_name');
        if ($request->isPost()){
            //更改退货地址
            $result = Shop::where(['member_id' => Session::get('member_id')])
                ->update(['bank_name' => $request->post('bank_name')]);
            return $result||$result === 0 ? ['code' => 200 , 'message' => '修改成功'] :[ 'code' => 0 ,'message'=>'修改失败'];
        }
        return $this->fetch('',[
            'bank_name' => $bank_name,
        ]);
    }
    /*
     * 修改银行名
     */
    public function edit_cardholder(Request $request)
    {
        //查找用户的银行
        $cardholder_name = Shop::where(['member_id' => Session::get('member_id')])->value('cardholder_name');
        if ($request->isPost()){
            //更改银行
            $result = Shop::where(['member_id' => Session::get('member_id')])
                ->update(['cardholder_name' => $request->post('cardholder_name')]);
            return $result||$result === 0 ? ['code' => 200 , 'message' => '修改成功'] :[ 'code' => 0 ,'message'=>'修改失败'];
        }
        return $this->fetch('',[
            'cardholder_name' => $cardholder_name,
        ]);
    }
    /*
     * 修改银行卡号
     */
    public function cardholder_number(Request $request)
    {
        //查找用户的银行卡号
        $cardholder_number = Shop::where(['member_id' => Session::get('member_id')])->value('cardholder_number');
        if ($request->isPost()){
            //更改银行卡号
            $result = Shop::where(['member_id' => Session::get('member_id')])
                ->update(['cardholder_number' => $request->post('cardholder_number')]);
            return $result||$result === 0 ? ['code' => 200 , 'message' => '修改成功'] :[ 'code' => 0 ,'message'=>'修改失败'];
        }
        return $this->fetch('',[
            'cardholder_number' => $cardholder_number,
        ]);
    }
    /*
     * 商品管理
     */
    public function goods_manage(Request $request,$search = '')
    {
        $shop = new ShopGoods();
        if ($request->isPost()){
            $goodsArr = [];
            $show = $request->post('show');
            $sort_type = $request->post('sort_type');
            $page = $request->post('page');
            $ids = $request->post('ids');
            $search = $request->post('search');
            if ($show == 'sale'){
                //查找本店铺出售中商品
                $goodsArr['data'] = $shop
                    ->where(['member_id'=>Session::get('member_id'),'state'=>1,'status'=>1])
                    ->where('id','not in',$ids)
                    ->where('title','like','%'.$search.'%')
                    ->field('id,member_id,title,price,thumb_img,sale_number,inventory,hits,rebate_percentage,cause,state,status')
                    ->order($sort_type." desc")
                    ->limit(($page-1)*5,5)
                    ->select();
                $goodsArr['pages'] = ceil($shop
                        ->where('title','like','%'.$search.'%')
                        ->where('id','not in',$ids)
                        ->where(['member_id'=>Session::get('member_id'),'state'=>1,'status'=>1])
                        ->count('id')/5);
            }elseif ($show == 'warehouse'){
                //查找本店铺仓库中商品
                $goodsArr['data'] = $shop
                    ->where(['member_id'=>Session::get('member_id'),'state'=>2])
                    ->where('id','not in',$ids)
                    ->where('title','like','%'.$search.'%')
                    ->field('id,member_id,title,price,thumb_img,sale_number,inventory,hits,rebate_percentage,cause,state,status')
                    ->order($sort_type." desc")
                    ->limit(($page-1)*5,5)
                    ->select();
                $goodsArr['pages'] = ceil($shop
                        ->where('title','like','%'.$search.'%')
                        ->where('id','not in',$ids)
                        ->where(['member_id'=>Session::get('member_id'),'state'=>2])
                        ->count('id')/5);
            }
            return $goodsArr;
        }
        //统计出售中商品的数量
        $sale_count = $shop->where('title','like','%'.$search.'%')->where(['member_id'=>Session::get('member_id'),'state'=>1,'status'=>1])->count('id');
        //统计仓库中的商品数量
        $warehouse_count = $shop->where('title','like','%'.$search.'%')->where(['member_id'=>Session::get('member_id'),'state'=>2])->count('id');
        return $this->fetch('',[
            'show'  =>  $request->param('show'),
            'sort_type' =>  $request->param('sort_type','sort'),
            'sale_count'    =>  $sale_count,
            'warehouse_count'    =>  $warehouse_count,
        ]);
    }
    /*
     * 上下架商品处理
     */
    public function sold_out(Request $request)
    {
        if ($request->isPost()){
            $shopGoods = new ShopGoods();
            $id = $request->post('id');
            Session::set('id',$id);
            //查询条件
            if ($request->post('type') == 1){
                $result = $shopGoods->where('id',$id)->update(['state'=>2]);
                return $result?['code'=>200,'message'=>'商品已下架']:['code'=>0,'message'=>'商品下架失败'];
            }elseif ($request->post('type') == 2){
                $result = $shopGoods->where('id',$id)->update(['state'=>1]);
                return $result?['code'=>200,'message'=>'商品已上架']:['code'=>0,'message'=>'商品上架失败'];
            }
        }
    }
    /*
     * 删除商品
     */
    public function destroy(Request $request)
    {
        if ($request->isPost()){
            $result = ShopGoods::destroy($request->post('id'));
            return $result?['code'=>200,'message'=>'删除成功']:['code'=>0,'message'=>'删除失败'];
        }
    }
    /*
     * 商品搜索展示页
     */
    public function goods_query()
    {
        return $this->fetch('');
    }
    /*
     * 订单管理
     */
    public function order_manage($type = '-1',$search = '',$search_type = 1)
    {
        $search_type = ($search_type == 1)?'shop_order_number':'title';
        $mold = ($type == -1)?'':['status'=>$type];
        $order = new  MemberOrder();
        //查询当前店铺当前类型的订单
        $arr = $order->where('shop_id',Session::get('member_id'))
            ->where($mold)
            ->where($search_type,'like','%'.$search.'%')
            ->with('memberOrderAttached')
//            ->field('id,create_time,status,title,picUrl,attr,number,price,shop_order_number')
            ->order('create_time desc')
            ->select();
//        return json($arr);
        //合并订单
        $res = array();
        foreach($arr as &$item) {
            $res[$item['shop_order_number']][] = $item;
        }
//        return json($res);
        $opt = [];
        foreach ($res as &$v){
            $zhi = 0;
            foreach ($v as $vv){
               if ($vv->memberOrderAttached) {
                   foreach ($vv->memberOrderAttached as $item){
                       $zhi += $item['number'];
                   }
               }
            }
            $opt[] = $zhi;
        }
//        return json(array_values($res));
        return $this->fetch('',[
            'res'   =>  array_values($res),
            'opt'   =>  $opt,
            'statistics'      =>  $order->statistics(Session::get('member_id'),$search,$search_type),
        ]);
    }
    /*
     * 订单查询展示页
     */
    public function order_query()
    {
        return $this->fetch('');
    }
    /*
     * 订单详情页
     */
    public function order_details($id,$type)
    {
        $status = ($type == -1)?'':['sun_member_order.status'=>$type];
        $orderArr = (new MemberOrder())
            ->where(['shop_order_number'=>$id])
            ->where($status)
            ->with(['shopGoods'=>function ($query){
                $query->withField('id,rebate_percentage');
            }])
            ->order('freight desc')
            ->select();
        $nickname = (new Member())->where('id',$orderArr[0]->member_id)->value('nickname');
        return $this->fetch('',[
            'orderArr'      =>  $orderArr,
            'nickname'      =>  $nickname,
        ]);
    }
    /*
     * 退款处理
     */
    public function refund()
    {
        return $this->fetch('');
    }
    /*
     * 评价管理
     */
    public function evaluate_manage(Request $request)
    {
        if ($request->isPost()){
            $model = new ShopGoodsEvaluate();
            $page = $request->post('page');
            //查找店铺评价
            $result['data'] = $model
                ->where(['shop_id' => Session::get('member_id')])
                ->with(['member' => function ($e){
                    $e
                        ->withField('id,nickname,avatar');
                }])
                ->limit(($page - 1) * 10 , 10)
                ->order(['create_time' => 'desc'])
                ->select();
            $result['data'] = array_map(function ($item){
                if ($item['picArr']){   //有图
                    $item['picArr'] = unserialize($item['picArr']);
                }
                return $item;
            },$result['data']);
            $result['pages'] = ceil($model->where(['shop_id' => Session::get('member_id')])->count() / 10);
            return $result;
        }
        return $this->fetch('');
    }
    /*
     * 回复评价
     */
    public function reply_content(Request $request)
    {
        if ($request->isPost()){
            $data = $request->post();
            //执行回复
            $result = (new ShopGoodsEvaluate())
                ->where(['id' => $data['id']])
                ->update(['reply' => $data['content'],'reply_status' => 1]);
            return $result? ['code' => 200 , 'message' => '回复成功']:['code' => 0 ,'message' => '回复失败'];
        }
    }
    /*
     * 历史回复
     */
    public function history_reply()
    {
        return $this->fetch('');
    }
}